<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.lt_id ? '修改标签类型' : '添加标签类型'" v-model="visible" append-to-body width="500px"
    @close="handleClose">
    <el-form ref="formRef" label-position="top">
      <el-form-item label="类型名称" :error="errorMsg" required>
        <el-input v-model="form.name" placeholder="请输入" class="w-full" @blur="handleBlur" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../../api'
import { ElMessage } from 'element-plus'
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const formRef = ref()
const errorMsg = ref('')

const handleBlur = () => {
  errorMsg.value = form.value.name ? '' : '类型名称不能为空'
}

const emit = defineEmits(['close', 'success'])

// 打开弹窗
const open = async (lt_id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  if (lt_id) {
    const res = await api.detailType({ lt_id })
    form.value = res.data
    formRef?.value?.clearValidate()
  } else {
    form.value = {}
    formRef?.value?.resetFields()
  }
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  if(!form.value.name) {
    errorMsg.value = '类型名称不能为空'
    return
  }
  loadings.submit = true
  api[form.value.lt_id ? 'updateType' : 'addType'](form.value).then(res => {
    const {code, message} = res
    if(code === 200) {
      ElMessage.success('操作成功')
      emit('success')
      close()
    } else {
      errorMsg.value = message
    }
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>